/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.web.gwt.basics.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import com.genia.toolbox.web.gwt.basics.context.GwtBasicsContext;
import com.genia.toolbox.web.spring.multipart.impl.AbstractRequestUploadListener;

/**
 * {@link com.genia.toolbox.web.spring.multipart.RequestUploadListener} to display
 * upload progress in Gwt Forms.
 */
public class GwtFileUploadListener
    extends AbstractRequestUploadListener
{

  /**
   * the <code>Log</code> variabe.
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(GwtFileUploadListener.class);

  /**
   * the context of the request.
   */
  private GwtBasicsContext context;



  /**
   * Updates the listeners status information.
   * 
   * @param pBytesRead
   *          the total number of bytes, which have been read so far
   * @param pContentLength
   *          the total number of bytes, which are being read. May be -1, if
   *          this number is unknown
   * @see org.apache.commons.fileupload.ProgressListener#update(long, long, int)
   */
  public void update(long pBytesRead, long pContentLength)
  {
    try {
      Long identifier = ServletRequestUtils.getLongParameter(context.getRequest(), "identifier");
      if (identifier != null) {
        int progress = new Long((pBytesRead * 100l) / pContentLength).intValue();
        context.setProgress(identifier, progress);
      }

    }
    catch (ServletRequestBindingException e) {
      LOGGER.error(e.getMessage(), e);
    }
  }



  /**
   * getter for the context property.
   * 
   * @return the context
   */
  public GwtBasicsContext getContext()
  {
    return context;
  }



  /**
   * setter for the context property.
   * 
   * @param context
   *          the context to set
   */
  public void setContext(GwtBasicsContext context)
  {
    this.context = context;
  }

}
